<?php

namespace app\schoolwall\controller;

use think\Controller;

class Star extends Controller
{
    protected $StarModel = null;
    protected $UserModel = null;
    protected $PostsModel = null;
    protected $tallModel = null;

    protected function _initialize()
    {
        $this->StarModel = model('common/User/Star');
        $this->UserModel = model('common/User/User');
        $this->PostsModel = model('common/Posts/Posts');
        $this->tallModel = model('common/Posts/Tall');
    }

    /**
     * 收藏列表
     */
    public function starlist()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->post('userid', 0, 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
        }

        $user = $this->UserModel->find($userid);

        if (!$user) {
            $this->error('用户不存在');
        }

        $count = $this->StarModel->where('userid', $userid)->count();
        $item = $this->StarModel->where('star.userid', $userid)->with('posts')->order('createtime desc')->page($page, $limit)->select();
        // halt($item);

        // 循环$item，添加user
        foreach ($item as $key => $value) {
            $item[$key]['posts']['user'] = $this->UserModel->find($value['posts']['userid']);
        }

        //循环$item，判断是否点赞过，是则在数组中添加is_like字段，值为1，否则为0
        foreach ($item as $key => $value) {
            $arr = explode(',', $value['posts']['likes']);
            if (in_array($userid, $arr)) {
                $item[$key]['posts']['is_like'] = true;
            } else {
                $item[$key]['posts']['is_like'] = false;
            }
        }

        // 循环$item，判断是否收藏过，是则在数组中添加is_collect字段，值为1，否则为0
        foreach ($item as $key => $value) {
            $res = model('common/User/Star')->where('userid', $userid)->where('postid', $value['posts']['id'])->find();
            if ($res) {
                $item[$key]['posts']['star'] = true;
            } else {
                $item[$key]['posts']['star'] = false;
            }
        }

        //循环$item，找出留言，存在tall里面
        foreach ($item as $key => $value) {
            $tall = $this->tallModel->where('postid', $value['posts']['id'])->with('user')->order('createtime desc')->select();
            if (!$tall) {
                $item[$key]['posts']['tall'] = [];
            } else {
                $item[$key]['posts']['tall'] = $tall;
            }
        }

        $data = [
            'count' => $count,
            'item' => $item,
        ];

        if ($item) {
            return $this->success('获取成功', '', $data);
        } else {
            return $this->error($this->PostsModel->getError());
        }
    }
}
